const { pool, router, resJson } = require('../connect')
const commentSQL = require('../db/commentSQL')


router.post('/commentUp', function (req, res) {
  let _req = req;
  let _res = res;
  let point = {
    user_id: _req.body.userid,
    comment: _req.body.comment,
    user_name: _req.body.username,
    create_time: _req.body.createtime
  }
  console.log(point);
  let _data;
  pool.getConnection((err, conn) => {
    conn.query(commentSQL.insert, point, (err, result) => {
      if (result) {
        _data = {
          msg: '上传成功'
        }
      } else {
        _data = {
          code: -1,
          msg: '上传失败'
        }
      }
    })
    setTimeout(() => {
      resJson(_res, _data)
    }, 200);
    pool.releaseConnection(conn)
  })
})

  .get('/allComment', function (req, res) {
    let _res = res;
    let _data;
    pool.getConnection((err, conn) => {
      conn.query(commentSQL.queryAll, (e, r) => {
        if (e) _data = {
          code: -1,
          msg: e
        }
        if (r) {
          if (r.length) {
            _data = {
              code: 1,
              msg: '查询成功',
              data: r
            }
          } else {
            _data = {
              code: -1,
              msg: '暂无记录'
            }
          }
        }
        setTimeout(() => {
          resJson(_res, _data)
        }, 200);
      })
      pool.releaseConnection(conn)
    })
  })

router.post('/deleteComment', (req, res) => {
  // 获取前台页面传过来的参数
  let _req = req;
  let point = {
    id: _req.body.id,
    user_id: _req.body.userid,
    comment: _req.body.comment,
    user_name: _req.body.username,
    create_time: _req.body.createtime
  }

  let _res = res;
  let _data;
  // 整合参数
  // 从连接池获取连接
  pool.getConnection((err, conn) => {
    conn.query(commentSQL.deleteComment, point.id, (err, result) => {
      if (err) _data = {
        code: -1,
        msg: e
      }
      if (result) {
        _data = {
          msg: '删除评论操作成功'
        }
      }
    })
    setTimeout(() => {
      //把操作结果返回给前台页面
      resJson(_res, _data)
    }, 200);
    pool.releaseConnection(conn) // 释放连接池，等待别的连接使用
  })
})
module.exports = router;